//
//  ZGuessController.m
//  NewProject
//
//  Created by 陈洪鑫 on 2018/4/13.
//  Copyright © 2018年 chenIos. All rights reserved.
//

#import "ZWalletDetailController.h"
//#import "ZBaseTableView.h"
#import "ZChangeWalletController.h"
#import "ZMyListCell.h"
#import "ZWalletSubTitleCell.h"
#import "ZWalletDetaiHeadCell.h"
#import "ZWalletDetailItem.h"
#import "ZChangePasswordController.h"
#import "ZExportPrivateView.h"
//#import ""
#import "ZCreateWalletController.h"
#import "ZBaseNaviController.h"
#import "ZWalletInfo.h"
@interface ZWalletDetailController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>
//@property(nonatomic,strong)ZBaseTableView *tableView;
@property(nonatomic,strong)UICollectionView *collectionView;

@property (nonatomic,strong) ZWalletDetailItem *item;

@property (nonatomic,strong) UIView *titleView;
@property (nonatomic,strong) UILabel *titleLable;
@property (nonatomic,strong) UIButton *changeWalletBtn;
@property (nonatomic,strong) UIButton *deleteBtn;
@property(nonatomic,strong)ZWalletInfo *walletInfo;


@end

@implementation ZWalletDetailController
- (UIButton *)deleteBtn
{
    if (!_deleteBtn) {
    
        UIButton *deleteWalletBtn = [[UIButton alloc]init];
        [deleteWalletBtn setTitleColor:[UIColor colorWithHexString:@"#666666"] forState:UIControlStateNormal];
        [deleteWalletBtn addTarget:self action:@selector(deleteWalletAction) forControlEvents:UIControlEventTouchUpInside];
        [deleteWalletBtn setTitle:Z_Location(@"deleteWallet") forState:UIControlStateNormal];
        [deleteWalletBtn setBackgroundColor:[UIColor colorWithHexString:@"#eff1f2"]];
        deleteWalletBtn.layer.cornerRadius = 5;
        deleteWalletBtn.clipsToBounds = YES;
        [self.view addSubview:deleteWalletBtn];
        CGFloat bottom = iPhoneX ? 34 + 10 : 10;
        [deleteWalletBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(30);
            make.right.mas_equalTo(-30);
            make.bottom.mas_equalTo(-bottom);
            make.height.mas_equalTo(50);
        }];
        _deleteBtn = deleteWalletBtn;
        
    }return _deleteBtn;
}
- (UIButton *)changeWalletBtn
{
    if (!_changeWalletBtn) {
        _changeWalletBtn = [[UIButton alloc]init];
        [_changeWalletBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_changeWalletBtn addTarget:self action:@selector(switchWalletAction) forControlEvents:UIControlEventTouchUpInside];
        [_changeWalletBtn setTitle:Z_Location(@"switchAccount") forState:UIControlStateNormal];
        [_changeWalletBtn setBackgroundColor:RGBCOLOR(34, 156, 178)];
        _changeWalletBtn.layer.cornerRadius = 5;
        _changeWalletBtn.clipsToBounds = YES;
        [self.view addSubview:_changeWalletBtn];
        [_changeWalletBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(30);
            make.right.mas_equalTo(-30);
            make.bottom.mas_equalTo(self.deleteBtn.mas_top).mas_offset(-9);
            make.height.mas_equalTo(50);
        }];
    }return _changeWalletBtn;
}
- (UIView *)titleView
{
    if (!_titleView) {
        _titleView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_W, 64)];
        _titleView.backgroundColor = RGBCOLOR(250, 250, 250);
        UIButton *btn = [UIButton new];
        [btn setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
        [btn setTintColor:[UIColor grayColor]];
        
        [btn addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
        UILabel *label = [UILabel new];
        label.text = self.account.name;
        label.textColor = [UIColor colorWithHexString:@"#4e5d6f"];
        label.font = H2;
        _titleLable = label;
        UIButton *saveBtn = [[UIButton alloc]init];
//        [saveBtn setTitle:Z_Location(@"save") forState:UIControlStateNormal];
        [saveBtn setTitleColor:RGBCOLOR(63, 185, 199) forState:UIControlStateNormal];
        [saveBtn addTarget:self action:@selector(saveAction) forControlEvents:UIControlEventTouchUpInside];
        [_titleView addSubview:btn];
        [_titleView addSubview:label];
        [_titleView addSubview:saveBtn];
        [btn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(0);
            make.bottom.mas_equalTo(-10);
            make.width.mas_equalTo(50);
        }];
        __weak typeof(_titleView) weakView = _titleView;
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.mas_equalTo(weakView.mas_centerX);
            make.centerY.mas_equalTo(btn.mas_centerY);
        }];
        [saveBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_equalTo(-10);
            make.bottom.mas_equalTo(-10);
        }];
        
    }return _titleView;
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
}
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    self.navigationController.navigationBarHidden = YES;
}
- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    
    self.navigationController.navigationBarHidden = NO;
}
#pragma mark -- saveAction
- (void)saveAction{
    
}
- (void)switchWalletAction{
    [ZDBManager changeSelectedWallet:self.account.walletAdress completion:^(BOOL isSuccess) {
        if (isSuccess) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"z_wallet_pais_change" object:nil];
        }
    }];
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)goBack{
    [self.navigationController popViewControllerAnimated:YES];
}
- (UICollectionView *)collectionView
{
    if (!_collectionView) {
//        CGFloat navHeight = iPhoneX ? 44 : 20;
        CGFloat y = CGRectGetMaxY(self.titleView.frame);
        
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, y, SCREEN_W, SCREEN_H - y) collectionViewLayout:[UICollectionViewFlowLayout new]];
        _collectionView.backgroundColor = [UIColor clearColor];
        [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"UICollectionViewCell"];
        
        [_collectionView registerNib:[UINib nibWithNibName:@"ZMyListCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:@"ZMyListCell"];
         [_collectionView registerNib:[UINib nibWithNibName:@"ZWalletDetaiHeadCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:@"ZWalletDetaiHeadCell"];
        
        [_collectionView registerNib:[UINib nibWithNibName:@"ZWalletSubTitleCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:@"ZWalletSubTitleCell"];
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
    }return _collectionView;
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.item = [ZWalletDetailItem new];
//    self.item.totalMoney = @"0";
//    self.item.privateCode = @"fadslfjaskldjfkasjdflkjaslfjs";
    self.item.items = [ZWalletDetailInfoItem getInfos];
    self.title = self.account.name;
    [self.view addSubview:self.titleView];
    [self.view addSubview:self.collectionView];
    [self deleteBtn];
    [self changeWalletBtn];
    self.changeWalletBtn.hidden = self.account.isSelected;
    [self requestCoinNumberData:self.account];
}
-(void)requestCoinNumberData:(ZWalletAccountInfo *)accountInfo
{
    ZWWeakSelf;
    NSString *url = [NSString stringWithFormat:@"%@wallet/getAssetList",PortServer];
    NSDictionary *param  = @{@"address":accountInfo.walletAdress};
    ZWLog(@"url = %@\n param = %@",url,param);
    [ZNetManager GET:url parameters:param success:^(NSURLSessionDataTask *task, id  _Nullable responseObject) {
        NSInteger status = [responseObject[@"status"] integerValue];
        if(status == 1){
            ZWalletInfo *info = [ZWalletInfo mj_objectWithKeyValues:responseObject[@"data"]];
            weakSelf.walletInfo = info;
            [weakSelf.collectionView reloadData];
        }else
        {
            [ZProgressManager showError:responseObject[@"message"]];
        }
        ZWLog(@"responseObject = %@",responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError *error) {
        [ZProgressManager showError:@"连接失败"];
        ZWLog(@"error = %@",error.userInfo);
    }];
}
#pragma mark --- deleteWalletAction
- (void)deleteWalletAction{
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:Z_Location(@"deleteWallet") message:Z_Location(@"deleteWalletWarning") preferredStyle:(UIAlertControllerStyleAlert)];
    UIAlertAction *action = [UIAlertAction actionWithTitle:Z_Location(@"cancel") style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
        
    }];
//    ZWWeakSelf;
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:Z_Location(@"confirm") style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        //删除钱包操作
        [ZDBManager deleteWallet:self.account.walletAdress completion:^(BOOL isSuccess, BOOL isHasWallet) {
            if (isSuccess) {
                [ZProgressManager showSuccess:Z_Location(@"deleteSuccess")];
            }
            if (isHasWallet) {
                [[NSNotificationCenter defaultCenter] postNotificationName:@"z_wallet_pais_change" object:nil];
                [self.navigationController popViewControllerAnimated:YES];
            }else
            {
                [UIApplication sharedApplication].keyWindow.rootViewController = [[ZBaseNaviController alloc]initWithRootViewController:[ZCreateWalletController new]];
            }
            
        }];
    }];
    [alert addAction:action];
    [alert addAction:action1];
    [self presentViewController:alert animated:YES completion:nil];

}

#pragma mark -- UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 2;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    switch (section) {
        case 0:
            return 1;
            break;
        case 1:
            return self.item.items.count;
            break;
        default:
            return 0;
            break;
    }
   
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.section) {
        case 0:
        {
            ZWalletDetaiHeadCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ZWalletDetaiHeadCell" forIndexPath:indexPath];
            if(self.walletInfo){
                NSString *str = [NSString stringWithFormat:@"%.2lf %@",[self.walletInfo.total doubleValue],[ZWalletAccount wallet].currentCurrrencyUnit];
                cell.titleLabel.text = str;
            }
            cell.subTitleLabel.text = self.account.walletAdress;
            return cell;
        }
            break;
        case 1:
        {
            
            ZWalletDetailInfoItem *item = self.item.items[indexPath.item];
            if ([item.tagName isEqualToString:Z_Location(@"walletName")]) {
                ZWalletSubTitleCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ZWalletSubTitleCell" forIndexPath:indexPath];
                cell.titleLabel.text = item.tagName;
                cell.subTitleTF.text = self.account.name;
                return cell;
            }else{
                ZMyListCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ZMyListCell" forIndexPath:indexPath];
                [cell.titleBtn setTitle:item.tagName forState:UIControlStateNormal];
                return cell;
            }
        }
            break;
     
        default:
            return NULL;
            break;
    }

}


#pragma mark -- UICollectionViewDelegate

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section) {
        ZWalletDetailInfoItem *item = self.item.items[indexPath.item];
        if ([item.tagName isEqualToString:Z_Location(@"changePassword")]) {
            ZChangePasswordController *changeVC = [ZChangePasswordController new];
            changeVC.accout = self.account;
            [self.navigationController pushViewController:changeVC animated:YES];
        }else if ([item.tagName isEqualToString:Z_Location(@"exportPrivateKey")]){
            [self exportPrivateAction];
        }
    }
    
}

- (void)exportPrivateAction{
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:Z_Location(@"enterPassword") message:nil preferredStyle:(UIAlertControllerStyleAlert)];
    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
    }];
    UIAlertAction *action = [UIAlertAction actionWithTitle:Z_Location(@"cancel") style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    ZWWeakSelf;
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:Z_Location(@"confirm") style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        //对比密码是否进入下个环节
        if ([alert.textFields.firstObject.text isEqualToString:self.account.password]) {
            [ZProgressManager show];
            
           NSString *privateKey =  self.account.privateKey;
            [ZProgressManager dismiss];
            if (privateKey) {
                [weakSelf entryPrivateAlert:privateKey];
            }else
            {
                [ZProgressManager showError:Z_Location(@"导出失败")];
            }
           
        }else
        {
            [ZProgressManager showError:@"密码输入不正确"];
        }
        NSLog(@"%@",alert.textFields.firstObject.text);
        
    }];
    [alert addAction:action];
    [alert addAction:action1];
    
    
    [self presentViewController:alert animated:YES completion:nil];

}

-(void)entryPrivateAlert:(NSString *)privateStr{    
    ZExportPrivateView *privateView = [ZExportPrivateView exportView];
    privateView.privateLabel.text = privateStr;
    privateView.frame = [UIScreen mainScreen].bounds;
    [[UIApplication sharedApplication].keyWindow addSubview:privateView];

}
#pragma mark -- UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    CGFloat width = SCREEN_W;
    CGFloat height = 180;
    if (indexPath.section) {
        ZWalletDetailInfoItem *item = self.item.items[indexPath.item];
        if ([item.tagName isEqualToString:Z_Location(@"walletName")]) {
          
            return CGSizeMake(width, 70);
        }else{
            
             return CGSizeMake(width, 50);
        }
    }
    return CGSizeMake(width, height);
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsZero;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    if (section) {
        return 10;
    }
    return 0;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 0;
}
//- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section;
//- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section;



@end
